package com.jn.filter;

import com.jn.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权的拦截器
 *      1. 获取所有过滤器请求URL地址
 *      2. 判断是否是登录请求：/admin/login，如果是则放行
 *      3. 获取请求头，拿出token
 *      3.1 判断是否有token，如果没有，提示未授权
 *      3.2 如果有则继续执行
 *      4. 通过JwtUtil校验token
 *      4.1 如果没有通过校验则拦截
 *      4.2 如果通过了则继续
 *      5. 放行请求
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求URL地址,获取响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 如果是登录请求则放行
        if (request.getURI().getPath().contains("/admin/login")) {
            return chain.filter(exchange);
        }
        //3. 获取请求头 拿出token
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        //3.1 判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)) {
            //3.1.1. 响应中放入返回的状态吗, 没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //3.1.2. 返回
            return response.setComplete();
        }

        //4. 如果请求头中有令牌则解析令牌
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //e.printStackTrace();
            //4.1. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //4.2. 返回
            return response.setComplete();
        }
        //5. 放行
        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
